import {
  Form, Select, InputNumber, Button, Upload, Icon, Input, DatePicker, message,
} from 'antd';
import * as React from "react";


import styles from './GoodsAdd.css';
import TextArea from "antd/lib/input/TextArea";
import {GiftGoodsDomain} from "../../business/gift/GiftGoodsDomain";
import GiftGoodsService from "../../business/gift/GiftGoodsService";
import GiftManagerPros from "../pros/GiftManagerPros";
const {  RangePicker } = DatePicker;

const { Option } = Select;
const rangeConfig = {
  rules: [{ type: 'array', required: true, message: 'Please select time!' }],
};
class Demo extends React.Component<GiftManagerPros,any>{

  constructor(props){
    super(props)
    this.giftGoodsService = new GiftGoodsService();
    this.handleChange = this.handleChange.bind(this);
    this.getBase64 = this.getBase64.bind(this);
    this.handleChangeImage = this.handleChangeImage.bind(this);
    this.beforeUpload = this.beforeUpload.bind(this);
    this.dataChange =this.dataChange.bind(this);
    this.handleSubmit =this.handleSubmit.bind(this);
    this.uploadSuccess =this.uploadSuccess.bind(this);
  }
  giftGoodsService:GiftGoodsService;
  state = {
    loading: false,
    imageUrl:"",
    uploading:false,
    formGoods:new GiftGoodsDomain(),
    fileList:[],
    addLoading:false,
  };
  uploadSuccess(res,isSuccess){
    if(!isSuccess || res.code !="000000"){
      message.info(res.message);
    }else{
      message.info(res.message);
    }
    this.setState({
      addLoading:false,
    });

  }
  handleSubmit(e){
    e.preventDefault();
    // @ts-ignore
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if(this.state.fileList.length!=1){
          message.info("选择图片上传");
          return;
        }
        values.goodsImageName = this.state.formGoods.goodsImageName;
        values.beginTime = this.state.formGoods.beginTime;
        values.endTime = this.state.formGoods.endTime;
        values.timeRange = null;
        let token = sessionStorage.getItem('adminLoginToken');
        this.giftGoodsService.addGiftGoods(token,values,this.uploadSuccess);
        this.setState({
          addLoading:true,
        });
      }
    });


  }

  handleChange(event) {
    this.setState({ [event.target.name] : event.target.value});
  }
  getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleChangeImage(info){
    this.setState({fileList:info.fileList});
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      if(info.file.response.code !="000000"){
        message.info(info.file.response.message);
        info.fileList = [];
        this.setState({fileList:info.fileList});
      }
      this.state.formGoods.goodsImageName =info.file.response.data;
    }
  }

  dataChange(e,dateStrings){
    this.state.formGoods.beginTime =dateStrings[0];
    this.state.formGoods.endTime =dateStrings[1];

  }
  beforeUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }

    if(isLt2M){
      return true;
    }else{
      return false;
    }
  }
  images(imageUrl,uploadButton){
    return imageUrl != '' ? '' : uploadButton;
  }

  render() {
    // @ts-ignore
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const r: RegExp = /^[0-9]+$/;
    const imageUrl = this.state.imageUrl;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">添加图片</div>
      </div>
    );
    const dateFormat = 'YYYY-MM-DD';
    const {fileList,addLoading} = this.state;
    return (
      <div className={styles.normal}>
      <Form onSubmit={this.handleSubmit}>
        <div>
          <div className={styles.gift_info_title}>礼品信息</div>
        </div>
        <div className={styles.gift_base_info}>
          <div className={styles.gift_base_info_1}>
            <Form.Item
              {...formItemLayout}
              label="礼品名称"
            >
              {getFieldDecorator('goodsName',{rules: [
                  { required: true, message: '礼品名称不能为空', type:"string"},
                ],})(
                <Input />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="兑换积分"
            >
              {getFieldDecorator('goodsPoints',{rules: [
                  { required: true, message: '兑换积分不能为空且为数字',type:"string",pattern:r},
                ],})(
                <Input />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="库存"
            >
              {getFieldDecorator('goodsQuantity',{rules: [
                  { required: true, message: '库存不能为空且为数字', type: 'string' ,pattern:r},
                ],})(
                <Input />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="礼品标签"
            >
              {getFieldDecorator('goodsTag',{} )(
                <Input />
              )}
            </Form.Item>
          </div>
          <div className={styles.gift_base_info_2}>
              <Upload
                className="avatar-uploader"
                name="goodsImagesName"
                fileList={fileList}
                action={process.env.POINT_SHOPPING_URL+"/point-shopping/admin/goods/save-image"}
                listType="picture-card"
                beforeUpload={this.beforeUpload}
                onChange={this.handleChangeImage}>
                {fileList.length>=1 ? "" : uploadButton}
              </Upload>
          </div>
        </div>
        <div>
          <div className={styles.gift_info_title}>兑换要求</div>
        </div>
        <div className={styles.gift_base_info}>
          <div className={styles.gift_base_info_3}>
            <Form.Item
              {...formItemLayout}
              label="限制每会员兑换数量"
            >
              {getFieldDecorator('limitType', {
                rules: [
                  { required: true, message: '请选择是否限制', type: 'string' },
                ],
              })(
                <Select mode="limitType" placeholder="请选择是否限制">
                  <Option value="true">限制</Option>
                  <Option value="false">不限制</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="每会员兑换数量"
            >
              {getFieldDecorator('limitCount', { initialValue: 1 })(
                <InputNumber min={1} max={10} />
              )}
              <span className={styles.gift_info_span}> 个</span>
            </Form.Item>

            <Form.Item
              {...formItemLayout}
              label="起止时间"
            >
              {getFieldDecorator('timeRange', rangeConfig)(
                <RangePicker onChange={this.dataChange}/>
              )}
            </Form.Item>
          </div>
        </div>


        <div>
          <div className={styles.gift_info_title}>礼品描述</div>
        </div>
        <div className={styles.gift_base_info}>
          <div className={styles.gift_base_info_3}>
            <Form.Item
              {...formItemLayout}
              label="礼品描述"
            >
              {getFieldDecorator('content', {rules: [
                  { required: false, type: 'string' }]})(
                <TextArea />
              )}
            </Form.Item>
          </div>
        </div>
        <div className={styles.gift_base_info}>
          <div className={styles.gift_base_info_3}>
            <Form.Item
              wrapperCol={{ span: 12, offset: 6 }}
            >
              <Button type="primary" htmlType="submit" loading={addLoading}>Submit</Button>
            </Form.Item>
          </div>
        </div>

      </Form>
      </div>
    );
  }
}

// @ts-ignore
const GoodsAdd = Form.create({ name: 'validate_other' })(Demo);

export default GoodsAdd;
